package ru.silviasaint.fridge.server.handler;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.silviasaint.fridge.server.bean.Product;
import ru.silviasaint.fridge.server.bean.SubstanceUtils;
import ru.silviasaint.fridge.server.dao.ProductDao;
import ru.silviasaint.fridge.server.dao.impl.DaoException;
import ru.silviasaint.fridge.shared.bean.ProductSkinny;
import ru.silviasaint.fridge.shared.ingredients.SearchAction;
import ru.silviasaint.fridge.shared.ingredients.SearchResult;

import com.google.inject.Inject;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;

public class SearchActionHandler implements ActionHandler<SearchAction,SearchResult>{
	private Logger logger = LoggerFactory.getLogger(SearchActionHandler.class);
	@Inject private ProductDao dao;
	@Override
	public SearchResult execute(SearchAction action, ExecutionContext ex)
			throws ActionException {
		List<Product> products;
		try {
			List<Product> exclude = new ArrayList<Product>();
			for (ProductSkinny ps : action.getExclude()){
				Product product = new Product();
				product.fillFromSkinny(ps);
				exclude.add(product);
			}
			products = dao.getProducts(exclude, action.getName());
			SearchResult result = new SearchResult();
			result.setResult((List<ProductSkinny>) SubstanceUtils.convertToSkinny(products));
			return result;
		} catch (DaoException e) {
			throw new ActionException(e);
		}
	}

	@Override
	public Class<SearchAction> getActionType() {
		return null;
	}

	@Override
	public void undo(SearchAction action, SearchResult result, ExecutionContext ex)
			throws ActionException {

	}

}
